const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL('injected/js/ajax.injected.js'));
document.documentElement.appendChild(script);

script.addEventListener('load', () => {
  chrome.storage.local.get(['isGlobalOpen', 'groupRules'], (config) => {
    setCustomWindowMsg({ type: 'updateConfig', data: config });
  });
});


const iFrameWidth = '700px';

if (window.self === window.top) {

  document.onreadystatechange = () => {
    if (document.readyState === 'complete') {
      const iframe = document.createElement('iframe');
      iframe.className = "api-iframe-content";
      iframe.frameBorder = "none";
      iframe.src = chrome.runtime.getURL("popup/index.html");
      document.body.appendChild(iframe);
      let show = false;
      chrome.runtime.onMessage.addListener((msg, sender) => {
        if (msg.to === 'popupBox' && msg.type === 'switchPopup') {
          show = !show;
          iframe.style.setProperty('transform', show ? 'translateX(0)' : `translateX(${iFrameWidth})`, 'important');
        }
      });
    }
  }
}

chrome.runtime.onMessage.addListener(msg => {
  if (msg.to === 'content' && msg.type === 'updateConfig') {
    setCustomWindowMsg({ type: msg.type, data: msg.data });
  }
});

/**
 * 发送自定义消息
 * @param {消息内容} configMsg = {type: 'string', data: any}
 * @param {发送目的类型} msgTo 默认globalRulesConfigMsg是发给 ajax.indected更新拦截配置信息
 * @returns
 */
function setCustomWindowMsg(configMsg, msgTo = 'globalRulesConfigMsg') {
  if (!configMsg || !configMsg.type) {
    return;
  }
  window.dispatchEvent(new CustomEvent(msgTo, { detail: configMsg }));
}
